package com.example.myapplication.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplication.BR;
import com.example.myapplication.R;
import com.example.myapplication.common.CommonAdapter;
import com.example.myapplication.common.CommonRecyclerAdapter;
import com.example.myapplication.databinding.ListBinding;
import com.example.myapplication.repository.data.File;
import com.example.myapplication.repository.network.FileService;
import com.example.myapplication.viewModel.ListVm;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ListActivity extends AppCompatActivity {

    ListBinding binding;
    List<File> fileList = new ArrayList<>();

    CommonRecyclerAdapter adapter;

    String dir;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        initData();
        //官方初始化 不可更改
//        listVm = new ViewModelProvider(this,new ViewModelProvider.NewInstanceFactory()).get(ListVm.class);
        //绑定
        binding = DataBindingUtil.setContentView(this, R.layout.list);
        binding.setLifecycleOwner(this);
        adapter = new CommonRecyclerAdapter(this,this, R.layout.list_item, BR.file, fileList, true) {
            @Override
            public void click(ViewHolder holder, int position, View view) {
                File file = fileList.get(position);
                if(file.getIsDir() == 0){
                    Toast.makeText(getApplicationContext(),fileList.get(position).getFileName(),Toast.LENGTH_SHORT).show();
                }else{
//                    list("/"+file.getFileName());
                    Intent intent = new Intent(ListActivity.this,ListActivity.class);
                    Bundle bundleSimple = new Bundle();
                    bundleSimple.putString("dir", "/".equals(dir)?dir+file.getFileName():dir+"/"+file.getFileName());
                    intent.putExtras(bundleSimple);
                    startActivity(intent);
                }
            }
        };
        binding.listView.setAdapter(adapter);
        Bundle bunde = this.getIntent().getExtras();
        dir = bunde != null?bunde.getString("dir"):"/";

        list(dir);
    }


    private void list(String dir){
        //创建 OkHttp 实例，添加日志拦截器，以便调试
        OkHttpClient client = new OkHttpClient().newBuilder().addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)).build();
//        创建 Retrofit 实例，配置 baseUrl, 添加 ConverterFactory。
        Retrofit retrofit = new Retrofit.Builder().
                baseUrl("https://pan.baidu.com")
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();
        //创建 Service 实例
        FileService fileService = retrofit.create(FileService.class);
        //创建 Call 实例
        fileService.list("list", "121.a0525002951f1ddc87ab02361d76c41a.YlHrbdiR_4GFf4IsHuXY8QEresPwldU31d-LT2w.8iYEHg", dir).enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                JsonObject res = response.body();
                Log.i("object:", res.toString());
                if (res.get("errno").getAsInt() == 0) {
                    JsonArray array = res.getAsJsonArray("list");
                    for (JsonElement temp : array) {
                        JsonObject tempAsJsonObject = temp.getAsJsonObject();
                        File file = new File();
                        file.setFileName(tempAsJsonObject.get("server_filename").getAsString());
                        file.setSize(tempAsJsonObject.get("size").getAsInt());
                        file.setIsDir(tempAsJsonObject.get("isdir").getAsInt());
                        file.setCategory(tempAsJsonObject.get("category").getAsInt());
                        fileList.add(file);
                    }
                    adapter.notifyDataSetChanged();
                } else {
                    Toast.makeText(ListActivity.this, "请求失败，请检查网络", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {
                Log.e("訪問失敗", "訪問失敗");
            }
        });
    }


}





